#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
from utils import log
import json
from config import etc
from controls import data_img_base_mysql
from controls import data_sight_desc_title_mysql
from controls import data_product_desc_title_mysql
from controls import data_app_ver_mysql
from controls import data_app_ver_mongo
from utils import fdfs
from utils import file_util
from utils.session_base import ApiGuest
from utils.session_mc import BaseHandler
from config.app_file_conf import file_op_type_add
from config.app_file_conf import file_op_type_upd

addItemCount=5
'''
仅供后台使用，更新脚本信息
path : /api/app/updatefile
'''
class AppFileUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        try :
            all_descs = data_sight_desc_title_mysql.get_sight_desc_title_all();
            descid = 0
            descs_html = '==================== sight_desc_title ====================<br/>'
            if all_descs :
                for item in all_descs :
                    descid = item['descid']
                    descs_html += 'descid:<input type="text" name="descid'+str(descid)+'" value="'+str(descid)+'" style="width:20;" readonly = "readonly"/>'
                    descs_html += 'title:<input type="text" name="title'+str(descid)+'" value="'+item['title']+'" style="width:200;" />'
                    descs_html += 'type:<select onchange="" name="type'+str(descid)+'"><option value="0">none</option><option value="1">update</option></select>'
                    descs_html += 'icon:<input type="file" name="descicon'+str(descid)+'"/>'
                    descs_html += '图标:<img src="'+item['imgurl']+'" height="15" width="15" /><br/>'
            
            descs_html += '<br/>==================== add new desc_title ====================<br/>'
            index = 1
            while index <= addItemCount :
                index += 1;
                descid += 1
                descs_html += 'descid:<input type="text" name="descid'+str(descid)+'" value="'+str(descid)+'" style="width:20;" readonly = "readonly"/>'
                descs_html += 'title:<input type="text" name="title'+str(descid)+'" value="" style="width:200;" />'
                descs_html += 'type:<select onchange="" name="type'+str(descid)+'"><option value="0">none</option><option value="1">update</option></select>'
                descs_html += 'icon:<input type="file" name="descicon'+str(descid)+'"/><br/>'
        
            self.write('''
                <html>
                <head><title>Upload Sight desc</title></head>
                <body>
                <form action='/api/app/updatefile' enctype="multipart/form-data" method='post'>
                ''' 
                + descs_html +
                '''
                <br/><input type='submit' value='submit'/>
                </form>
                </body>
                </html>
                ''')
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return


    def post(self) :
    
        #add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
        update_detail_list = []
        # app version info update
        from app_file_conf import sight_desc_icon_path
        from app_file_conf import sight_desc_icon_name
        try :
            #log.i(self.request)
            all_descs = data_sight_desc_title_mysql.get_sight_desc_title_all();
            descs_dict = {}
            if all_descs :
                descs_dict = {  item['descid'] : item for item in all_descs }
            total_count = addItemCount + len(all_descs)
            

            index = 1
            while index <= total_count :
                descid = index
                index += 1
                cur_descid = self.get_argument( 'descid'+str(descid) )
                cur_title = self.get_argument( 'title'+str(descid) )
                cur_type = int(self.get_argument( 'type'+str(descid) ) )
                if cur_type == 0 :
                    continue
                if not cur_title :
                    continue
                #log.i(str(cur_descid) + '====' + str(cur_title) + '====' +str(cur_type))
                cur_file_meta = None
                try :
                    cur_file_meta = self.request.files['descicon'+str(descid)][0]
                except Exception as e :
                    pass

                desc_item = { 'title' : cur_title }
                # if icon file is none
                if not cur_file_meta :
                    if descs_dict and descid in descs_dict : 
                        #log.i(desc_item)
                        data_sight_desc_title_mysql.update_title_by_descid( descid, desc_item )
                    continue

                # if update a icon file
                res = file_util.file_upload( cur_file_meta )
                print res
                if res['ret'] == 0 and res['res']:
                    img_dict = res['res']
                    desc_item['imgid']=img_dict['imgid']
                    desc_item['imgurl']='http://static.shitouren.com/group'+str(img_dict['group'])+'/'+img_dict['path']+'.'+img_dict['ext']

                    # x.png
                    filename = sight_desc_icon_name.replace('filename', str(descid))
                    #add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
                    update_detail = {'path': sight_desc_icon_path, 'filename': filename, 'url': desc_item['imgurl']}
                    # update
                    if descs_dict and descid in descs_dict : 
                        upd_res = data_sight_desc_title_mysql.update_title_by_descid( descid, desc_item )
                        if not upd_res :
                            continue
                        update_detail['optype'] = file_op_type_upd
                        update_detail_list.append( update_detail )
                        
                        # delete old img in fdfs
                        try :
                            imgid = descs_dict[descid]['imgid']
                            img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )
                        
                            p_group = str(img_base_item['group'])
                            file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                            #file_id_100 = img_base_item['path'] + '_100' + '.'+ img_base_item['ext']
                            #file_id_300 = img_base_item['path'] + '_300' + '.'+ img_base_item['ext']
                            
                            del_res = fdfs.delete_file_by_group_file_id( p_group, file_id )
                            #fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
                            #fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
                            
                            # if fdfs delete success, then delete imgid in img_base table
                            if del_res :
                                data_img_base_mysql.delete_img_base_by_imgid(imgid)
                        except Exception as e :
                            log.exp(e)
                    # insert
                    else :
                        desc_item['descid'] = descid
                        upd_res = data_sight_desc_title_mysql.add_sight_desc_title_item( desc_item )
                        if not upd_res :
                            continue
                        update_detail['optype'] = file_op_type_add
                        update_detail_list.append( update_detail )
                    
                else : # icon file update failure
                    data_sight_desc_title_mysql.update_title_by_descid( descid, desc_item )

                # { "ret" : 0, "msg" : "ok", "res" : dst_res }
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
            
        finally :
            if update_detail_list :
                addAppVersion(update_detail_list)
 
        return self.redirect( r"/api/app/updatefile" )

def addAppVersion( update_detail_list ) :
    if not update_detail_list :
        return False
    new_ver = None
    while True :
        # get latest app_ver
        latest_ver_dict = data_app_ver_mysql.get_latest_app_ver()
        latest_ver = latest_ver_dict['appver']
        tiny_ver = int( latest_ver.split('.')[2] )
        tiny_ver += 1
        new_ver = latest_ver.split('.')[0] + '.' + latest_ver.split('.')[1] + '.' + str(tiny_ver)
    
        item = {'appver':new_ver, 'status': 0}
        if data_app_ver_mysql.add_app_ver_item( item ) :
            break
    
    #add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
    upd_res = data_app_ver_mongo.add_detail_for_app_ver( new_ver, update_detail_list )
    if upd_res :
        data_app_ver_mysql.update_status_by_app_ver( new_ver, 1 ) 
    

'''
获取比客户端新的App版本修改信息。
传入参数：客户端版本号
path : /api/app/getnewver
'''
class NewVerHandler(tornado.web.RequestHandler) :

    @ApiGuest
    def post( self ) :
        #userid = self.ss_params['userid']  #userid发起浏览请求的登录用户id
        client_app_ver = self.ss_ver
        app_ver_dict = data_app_ver_mysql.get_latest_valid_app_ver( )
        if not app_ver_dict or app_ver_dict['appver'] == client_app_ver :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': {} } 
            self.write( json.dumps(res) )
            self.finish()
            return
        
        upd_list = data_app_ver_mongo.get_all_details_from_app_ver( client_app_ver )

        merge_upd_list = merge_app_vers( upd_list )
        res_dict = {"appver": app_ver_dict['appver'], "detail": merge_upd_list}
        
        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':res_dict } 
        self.write( json.dumps(res) )
        self.finish()
        return

def merge_app_vers( upd_list ) :
    if not upd_list :
        return None
    res_dict = {}
    for appver in upd_list :
        detail_list = appver['detail']
        if not detail_list :
            continue
        for update_item in detail_list :
            upd_file = update_item['path'] + update_item['filename']
            if upd_file in res_dict :
                first_type = res_dict[upd_file]['optype']
                if first_type == 1 and update_item['optype'] == 3:
                    del res_dict[upd_file]
                    continue
                if first_type == 1 and update_item['optype'] == 2 :
                    update_item['optype'] = first_type
            
            res_dict[upd_file] = update_item
            
    return res_dict.values();
    

'''
仅供后台使用，更新脚本信息
path : /api/app/updproductdesc
'''
class ProductDescUpdateHandler(tornado.web.RequestHandler) :

    def get(self) :
        try :
            all_descs = data_product_desc_title_mysql.get_product_desc_title_all();
            descid = 0
            descs_html = '==================== product_desc_title ====================<br/>'
            if all_descs :
                for item in all_descs :
                    descid = item['descid']
                    descs_html += 'descid:<input type="text" name="descid'+str(descid)+'" value="'+str(descid)+'" style="width:20;" readonly = "readonly"/>'
                    descs_html += 'title:<input type="text" name="title'+str(descid)+'" value="'+item['title']+'" style="width:100;" />'
                    descs_html += '颜色RGB(十六进制):<input type="text" name="color'+str(descid)+'" value="'+item['color']+'" style="width:60;color:'+item['color']+'" onblur="if(value.length!=0){this.style.color=value}" />'
                    descs_html += 'type:<select onchange="" name="type'+str(descid)+'"><option value="0">none</option><option value="1">update</option></select>'
                    descs_html += 'icon:<input type="file" name="descicon'+str(descid)+'"/>'
                    descs_html += '图标:<img src="'+item['imgurl']+'" height="15" width="15" /><br/>'
            
            descs_html += '<br/>==================== add new desc_title ====================<br/>'
            index = 1
            while index <= addItemCount :
                index += 1;
                descid += 1
                descs_html += 'descid:<input type="text" name="descid'+str(descid)+'" value="'+str(descid)+'" style="width:20;" readonly = "readonly"/>'
                descs_html += 'title:<input type="text" name="title'+str(descid)+'" value="" style="width:100;" />'
                descs_html += '颜色RGB(十六进制):<input type="text" name="color'+str(descid)+'" value="ff0000" style="width:60;color:ff0000" onblur="if(value.length!=0){this.style.color=value}"/>'
                descs_html += 'type:<select onchange="" name="type'+str(descid)+'"><option value="0">none</option><option value="1">update</option></select>'
                descs_html += 'icon:<input type="file" name="descicon'+str(descid)+'"/><br/>'
        
            self.write('''
                <html>
                <head><title>Update product desc title</title></head>
                <body>
                <form action='/api/app/updproductdesc' enctype="multipart/form-data" method='post'>
                ''' 
                + descs_html +
                '''
                <br/><input type='submit' value='submit'/>
                </form>
                </body>
                </html>
                ''')
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return


    def post(self) :
    
        ##add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
        #update_detail_list = []
        ## app version info update
        #from app_file_conf import product_desc_icon_path
        #from app_file_conf import product_desc_icon_name
        try :
            #log.i(self.request)
            all_descs = data_product_desc_title_mysql.get_product_desc_title_all();
            descs_dict = {}
            if all_descs :
                descs_dict = {  item['descid'] : item for item in all_descs }
            total_count = addItemCount + len(all_descs)

            index = 1
            while index <= total_count :
                descid = index
                index += 1
                cur_descid = self.get_argument( 'descid'+str(descid) )
                cur_title = self.get_argument( 'title'+str(descid) )
                cur_color = self.get_argument( 'color'+str(descid) )
                cur_type = int(self.get_argument( 'type'+str(descid) ) )
                if cur_type == 0 :
                    continue
                if not cur_title :
                    continue
                if not cur_color :
                    continue
                #log.i(str(cur_descid) + '====' + str(cur_title) + '====' +str(cur_type))
                cur_file_meta = None
                try :
                    cur_file_meta = self.request.files['descicon'+str(descid)][0]
                except Exception as e :
                    pass

                desc_item = { 'title':cur_title, 'color':cur_color }
                # if icon file is none
                if not cur_file_meta :
                    if descs_dict and descid in descs_dict : 
                        #log.i(desc_item)
                        data_product_desc_title_mysql.update_title_by_descid( descid, desc_item )
                    else :
                        desc_item['descid'] = cur_descid
                        desc_item['imgid'] = 0
                        desc_item['imgurl'] = ''
                        data_product_desc_title_mysql.add_product_desc_title_item( desc_item )
                    continue

                # if update a icon file
                res = file_util.file_upload( cur_file_meta )
                print res
                if res['ret'] == 0 and res['res']:
                    img_dict = res['res']
                    desc_item['imgid']=img_dict['imgid']
                    desc_item['imgurl']='http://static.shitouren.com/group'+str(img_dict['group'])+'/'+img_dict['path']+'.'+img_dict['ext']

                    ## x.png
                    #filename = product_desc_icon_name.replace('filename', str(descid))
                    ##add_detail_for_app_ver('2.1.1', [{'path': 'path1_1', 'filename': 'filename1_1', 'optype': '1', 'url': 'url1_1'}])
                    #update_detail = {'path': product_desc_icon_path, 'filename': filename, 'url': desc_item['imgurl']}
                    # update
                    if descs_dict and descid in descs_dict : 
                        upd_res = data_product_desc_title_mysql.update_title_by_descid( descid, desc_item )
                        if not upd_res :
                            continue
                        #update_detail['optype'] = file_op_type_upd
                        #update_detail_list.append( update_detail )

                        # delete old img in fdfs
                        try :
                            imgid = descs_dict[descid]['imgid']
                            img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )
                        
                            p_group = str(img_base_item['group'])
                            file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                            del_res = fdfs.delete_file_by_group_file_id( p_group, file_id )
                            
                            # if fdfs delete success, then delete imgid in img_base table
                            if del_res :
                                data_img_base_mysql.delete_img_base_by_imgid(imgid)
                        except Exception as e :
                            log.exp(e)
                    # insert
                    else :
                        desc_item['descid'] = descid
                        upd_res = data_product_desc_title_mysql.add_product_desc_title_item( desc_item )
                        if not upd_res :
                            continue
                        #update_detail['optype'] = file_op_type_add
                        #update_detail_list.append( update_detail )
                    
                else : # icon file update failure
                    data_product_desc_title_mysql.update_title_by_descid( descid, desc_item )

                # { "ret" : 0, "msg" : "ok", "res" : dst_res }
        except Exception as e :
            log.exp(e)
            res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
            
        finally :
            pass
            #if update_detail_list :
            #    addAppVersion(update_detail_list)
 
        return self.redirect( r"/api/app/updproductdesc" )
    
class ApiNotFoundHandler( BaseHandler ) :

    def get( self ) :
        raise tornado.web.HTTPError( 503 )

    @tornado.web.asynchronous
    def post( self ) :
        log.i( '503' )
        res = { 'idx':-1, 'ret':-5, 'msg':etc.err_no_api, 'res':{} }
        self.write( json.dumps(res) )
        self.finish()


